<?php

namespace Database\Seeders;

use App\Models\User;
use App\Models\Dish;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class UserFavoriteSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // 获取所有用户和菜品
        $users = User::all();
        $dishes = Dish::where('is_available', true)->get();
        
        if ($users->isEmpty() || $dishes->isEmpty()) {
            $this->command->warn('没有用户或菜品数据，请先运行相关Seeder');
            return;
        }
        
        $favorites = [];
        
        // 为每个用户随机收藏1-10个菜品（不超过可用菜品数量）
        foreach ($users as $user) {
            $maxFavorites = min(10, $dishes->count());
            $favoriteCount = rand(1, $maxFavorites);
            $favoriteDishes = $dishes->random($favoriteCount);
            
            foreach ($favoriteDishes as $dish) {
                $favorites[] = [
                    'user_id' => $user->id,
                    'dish_id' => $dish->id,
                    'created_at' => now()->subDays(rand(0, 30)),
                    'updated_at' => now()->subDays(rand(0, 30)),
                ];
            }
        }
        
        // 批量插入收藏数据
        DB::table('user_favorites')->insert($favorites);
        
        $this->command->info('已创建 ' . count($favorites) . ' 个用户收藏数据');
    }
}
